package com.rpoonolly.simplegame.mapio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.rpoonolly.simplegame.core.GameMap;
import com.rpoonolly.simplegame.core.MapFileManager;

public class SuperSimpleMapFileMngr implements MapFileManager<GameMap> {
	private File file;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	
	@Override
	public GameMap loadMap(String filename) throws IOException {
		file = new File(filename);
		if (!file.exists() || !file.isFile())
			throw new IOException("unable to find map file");
		
		in = new ObjectInputStream(new FileInputStream(file));
		try {
			return (GameMap) in.readObject();
		} catch (ClassNotFoundException e) {
			throw new IOException(e.getMessage());
		} finally {
			in.close();
		}
	}

	@Override
	public void writeMap(GameMap map, String filename) throws IOException {
		file = new File(filename);
		out = new ObjectOutputStream(new FileOutputStream(file));
		
		try {
			out.writeObject(map);
		} finally {
			out.close();
		}
	}

}
